#!c:\perl\bin\perl;exe

use Getopt::Std;
use File::Basename;
getopts( "d:h", \%options ); 
sub usage(){
	print "Usage :\n";
	print "\t$0 -d DIRECTORY (directory you want to scan to obtain an HTML file)\n";
	exit(1);
}

sub getExtensions(){
	my @tab = ();
	my $file = "C:/Program Files/scripts/audio.file.extensions.txt";
	open(EXT,"$file") or die "Impossible d'ouvrir $file";
	while(<EXT>){
		chomp;
		s/\s//g;
		my @tmptab = split(/,/);
		@tab = (@tab , @tmptab);
	}
	return @tab;
}

sub IsAudioFile(){
	my $filename = $_[0];
	
	my @ext = &getExtensions();
	foreach $tmp (@ext){
		return 0 if ( $filename =~ /.*$tmp$/ );
	}

	return 1;
}


usage() if ( not defined $options{d} or $options{h});

sub dir2html(){
	my $dir = $_[0];
	opendir REP, "$dir" or die "impossible d'ouvrir le repertoire \"$dir\"";
	my @fichiers = readdir REP;
	closedir REP;
	print "$dir\n";
	unlink "$dir/list.m3u";
	foreach $entree (@fichiers){
	 next if ( ($entree eq "." or $entree eq "..") );
		 if ( -d "$dir/$entree"){
			&dir2html("$dir/$entree");
		 }
		 elsif (&IsAudioFile("$dir/$entree") == 0) {
			print "$dir/$entree\n";
			chop($dir) if ($dir =~ /.*\/$/);
			my $dirname = basename($dir);
			open(M3U,">>$dir/00-$dirname.m3u") or die "Impossible d'ouvrir le fichier \"$dir/00-$dirname.m3u\""; 
			print "Writing $dir/$entree to file $dir/00-$dirname.m3u\n";
			print M3U "$entree\n";
			close(M3U);
		 }
	 }
}
my $initdir = $options{d};
if ( ! -d $initdir ){
	print "Directory \"$initdir\" does not exist !!!\n";
	system("echo \"$initdir\" > c:\error.log");
	exit(1);
}

&dir2html($initdir);

